package com.heiyu.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.StringUtils;

public class DateUtils {

    public static String format(Date date, String format){
        if(date == null){
            return null;
        }
        if(StringUtils.isEmpty(format)){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static Integer getTimestamp(String time){
        long t = Long.valueOf(time);
        return Integer.valueOf(t/1000+"");
    }

    public static Date getTargetDate(Date baseDate,int day){
        Calendar c = GregorianCalendar.getInstance();
        c.setTime(baseDate);
        c.add(Calendar.DATE,day);
        return c.getTime();
    }

    public static Date parseDate(String date,String format){
        if(StringUtils.isEmpty(date)){
            return null;
        }
        if(date.length()<14){
            date+=" 00:00:00";
        }
        if(StringUtils.isEmpty(format)){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取两个时间的日期
    public static Integer diff(Date beginTime,Date endTime){
        Long diff =  (endTime.getTime()-beginTime.getTime())/86400000l;
        return diff.intValue();
    }

    public static Date getCurrent(){
        Calendar c = GregorianCalendar.getInstance();
        return c.getTime();
    }
}
